<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="fileInput" type="file">
</body>
<script>
    // 主文件 main.js
const worker = new Worker('uploadWorker.js');

// 添加对Worker错误的监听
worker.onerror = function(e) {
  console.error('Worker发生错误:', e);
};

worker.onmessage = function(e) {
  console.log('从Worker返回的消息:', e.data);
};

function handleFileUpload(file) {
  if (!file || !file.type.startsWith('image/')) {
    console.error('请选择有效的图片文件');
    return;
  }

  const chunkSize = 1024 * 1024; // 分割大小，例如5MB
  let currentChunk = 0;
  const chunks = [];
  const uploadPromises = [];

  while (currentChunk < file.size) {
    chunks.push(file.slice(currentChunk, Math.min(file.size, currentChunk + chunkSize)));
    currentChunk += chunkSize;
  }

  // 限制同时上传的chunk数量为3个，使用Promise.all处理并发
  chunks.forEach((chunk, index) => {
    uploadPromises.push(uploadChunk(chunk, index));
  });

  Promise.all(uploadPromises)
    .then(() => console.log('全部上传完成'))
    .catch((error) => console.error('上传过程中发生错误:', error));
}

function uploadChunk(chunk, index) {
  return new Promise((resolve, reject) => {
    // 将每个chunk发送至worker处理
    worker.postMessage({
      fileChunk: chunk,
      uploadUrl: 'http://127.0.0.1:3000/up',
      chunkIndex: index
    });
  });
}

// 监听文件选择器的改变
document.querySelector('#fileInput').addEventListener('change', function(event) {
  const file = event.target.files[0];
  handleFileUpload(file);
});
</script>
    <!-- <script src="./index.js"></script> -->
    <script src="./upload.js"></script>
</html>